import React, { ForwardedRef, forwardRef, useCallback, useImperativeHandle, useMemo, useRef, useState } from 'react';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import {
  LineChart,
} from 'echarts/charts';
import { ECharts, SeriesOption } from 'echarts';
import {
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  DataZoomComponent,
  MarkAreaComponent,
} from 'echarts/components';
import {
  CanvasRenderer,
} from 'echarts/renderers';
import { Empty } from 'antd';

const color = ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];

echarts.use(
  [TitleComponent, TooltipComponent, GridComponent, LegendComponent, ToolboxComponent, LineChart, CanvasRenderer, DataZoomComponent, MarkAreaComponent]
);

export interface Props{
  dataSetList?: {
    brand?: string;
    title?: string;
    dataGroup?: string;
    range: [number,number];
    dataSet: number[][]
  }[];
  error?: string;
}

function FreqChartViewer(props: Props) {
  const { dataSetList, error } = props;
  const {
    xMin = 20,
    xMax = 20000,
    xLog = true,
    yLog = false,
    yMin = null,
    yMax = null,
    maxYMin = null,
    minYMax = null,
  } = { yMin: 50, yMax: 120 };

  const chartOptions = useMemo(() => {
    if (!dataSetList?.length) {
      return undefined;
    }

    const xName = 'Freq(Hz)';
    

    const dataSet = dataSetList.reduce((total, item)=>{
      return total.concat(item.dataSet);
    },[] as number[][]);

    return {
      tooltip: {
        trigger: 'axis',
        formatter: (params: any[]) => {
          const name = dataSetList.find(item=>params[0].axisValue >= item.range[0] && params[0].axisValue <= item.range[1] )?.name;
          return `<div>
                ${name ? `${name}<br />` : ''}
                ${xName.trim()}：${params[0].axisValue}<br />
                ${params.sort((a, b) => b.value[1] - a.value[1]).map(item => {
            return `${item.marker}${item.seriesName}：${item.value[1]}`;
          }).join('<br />')}
            </div>`;
        },
      },
      grid: {
        top: 40,
        left: 50,
        right: (() => {
          let length = 0;
          Array.from(xName).map(function (char) {
            if (/^[\u4e00-\u9fa5]+$/.test(char)) {
              length += 2;
            } else {
              length++;
            }
          });
          return length * 7;
        })(),
        bottom: 35,
        containLabel: true,
      },
      xAxis: {
        type: xLog ? 'log' : 'value',
        boundaryGap: false,
        nameLocation: 'end',
        nameTextStyle: {
          padding: [15, 0, 0, 0],
        },
        min: xMin,
        max: xMax,
        axisLabel: {
          formatter: (value: number) => {
            if (value !== 0 && value % 1000 === 0) {
              return `${value / 1000}K`;
            }
            return value;
          },
        },
        minorTick: {
          splitNumber: 9,
        },
        minorSplitLine: {
          show: true,
        },
        name: xName,
      },
      yAxis: {
        type: yLog ? 'log' : 'value',
        min: (() => {
          if (yMin) {
            return yMin;
          }
          if (maxYMin) {
            return function (value) {
              return value.min < maxYMin ? value.min : maxYMin;
            }
          }
          return null
        })(),
        max: (() => {
          if (yMax) {
            return yMax;
          }
          if (minYMax) {
            return function (value) {
              return value.max > minYMax ? value.max : minYMax;
            }
          }
          return null;
        })(),
      },
      dataZoom: [
        {
          yAxisIndex: [0],
          filterMode: 'none',
          type: 'slider',
          left: 20,
          width: 20,
        },
        {
          xAxisIndex: [0],
          filterMode: 'none',
          type: 'slider',
          bottom: 10,
          height: 20,
        },
      ],
      series: [
        {
          data: dataSet,
          name: `SPL(dB)`,
          type: 'line',
          showSymbol: false,
          smooth: true,
          emphasis: {
            focus: 'self',
          },
          markArea: {
            label: {
              lineHeight: 14,
            },
            data: dataSetList.filter(item=>item.title).map((item, index)=>{
              return [
                {
                  itemStyle: {
                    color: color[index],
                    opacity: 0.1,
                  },
                  name: `${item.brand}\n${item.title}\n${item.dataGroup}`,
                  xAxis: item.range[0],
                },
                {
                  xAxis: item.range[1],
                }
              ]
            })
          }
        }
      ],

    };
  }, [dataSetList]);

  if(!dataSetList?.length) {
    return <Empty description={`${error ? `${error}，` : ''}完成选择后，即可查看频响曲线`} />;
  }

  return <div style={{
    padding: 24,
    ...(dataSetList?.length ? {
      backgroundColor: 'rgba(246,235,235,0.3)',
    } : undefined)
  }}>
    <ReactEChartsCore
      style={{
        width: '100%',
        height: 600
      }}
      echarts={echarts}
      option={chartOptions}
      notMerge
      lazyUpdate={true}
    />
  </div>;
};

export default FreqChartViewer;
